<?php
namespace app\api\service;
use think\Controller;
use think\Db;

class MemberFundAccount extends Controller {
    static protected $err_code = 0;
    // 获取用户资金账户列表接口
    static public function get_member_fund_account($param){
        if(!isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        try{
            $member_id = $param['member_id'];
            $member_fund_account = Db::table('mob_member_fund_account')->where('member_id', $member_id)->where('is_band', 1)->select();
//            foreach ($member_fund_account as $k => $v) {
//                $member_fund_account[$k]['account'] = str_repeat(str_repeat('*', 4) . ' ', 3) . substr($v['account'], -4);
//            }
            return ['data'=>$member_fund_account,'code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取用户资金账户详细信息接口
    static public function get_member_fund_account_info($param) {
        if(!isset($param['member_id']) || !isset($param['fund_account_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        try{
            $where['member_id'] = $param['member_id'];
            $where['id'] = $param['fund_account_id'];
            $member_fund_account_info = Db::table('mob_member_fund_account')->where($where)->find();
            return ['data'=>$member_fund_account_info,'code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    //添加、编辑用户资金账户接口
    static public function save_member_fund_account($param) {
        if(!isset($param['member_id']) ||
            !isset($param['type']) ||
            !isset($param['account']) ||
            !isset($param['phone']) ||
            !isset($param['householder'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        // 启动事务
        Db::startTrans();
        try{
            $data = [
                'type' => $param['type'],
                'account' => $param['account'],
                'householder' => $param['householder'],
                'phone' => $param['phone'],
                'add_time' => time(),
                'cert_id' => $param['id_card'],
            ];

            /*调用验证器 验证数据*/
            $validate = validate('MemberFundAccount');
            //检查资金账户是否已存在
            if (!$validate->check($data)) {
                self::$err_code = $validate->getError();
                throw new \Exception('FAULT');
            }

            // 查询银行卡是否已存在在
            $account = Db::table('mob_member_fund_account')->where('account', $param['account'])->find();
            if ($account) {
                if ($account['member_id'] == $param['member_id']) {   // 银行卡存在并且是自己的  将绑定状态改为1
                    Db::table('mob_member_fund_account')->where('id', $account['id'])->update(['is_band' => 1]);
                    Db::commit();  //提交事务   返回成功
                    return ['data'=>'','code'=>200,'msg'=> 'SUCCESS'];
                } else {
                    self::$err_code = 400088;
                    throw new \Exception('FAULT');
                }
            }
            
            if ($param['type'] == 3) {
                // 查询银行卡信息
                $query_bank_info = self::query_bank_info(['num' => $param['account'], 'member_id' => $param['member_id']]);
                if ($query_bank_info['code'] != 200) {
                    //dump($query_bank_info);
                    self::$err_code = $query_bank_info['code'];
                    throw new \Exception($query_bank_info['msg']);
                }

                //验证银行信息
                $data['bank_name'] = $query_bank_info['data']['bank'];
                $data['logo'] = $query_bank_info['data']['logo'];
                $data['bank_type'] = $query_bank_info['data']['type'];

                // 实名认证银行卡信息
                $certification_bank_param = [
                    'num' => $param['account'],
                    'member_id' => $param['member_id'],
                    'phone_num' => $param['phone'],
                    'acct_name' => $param['householder'],
                    'cert_id' => $param['id_card'],
                ];
                $certification_bank = self::certification_bank($certification_bank_param);
                if ($certification_bank['code'] != 200) {
                    //dump($certification_bank);
                    self::$err_code = $certification_bank['code'];
                    throw new \Exception($certification_bank['msg']);
                }
            }

            // 验证通过 删除银行卡信息
            unset($data['cert_id']);

            if ($fund_account_id = $param['fund_account_id'] > 0) {
                $where['member_id'] = $param['member_id'];
                $where['id'] = $param['fund_account_id'];
                Db::table('mob_member_fund_account')->where($where)->update($data);
            } else {
                $data['member_id'] = $param['member_id'];
                Db::table('mob_member_fund_account')->insert($data);
            }
            Db::commit();
            return ['data'=>'','code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 查询银行卡信息接口  内部调用
    static public function query_bank_info($param) {
        if(!isset($param['num']) || !isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            // 获取用户当天查询次数   检查当前用户的查询频率，防止刷接口  每人每天 上限10次
            $time = strtotime(date('Y-m-d'));// 当天0点时间戳
            $q_num = db('query_bank_log')->where('member_id', $param['member_id'])->whereTime('add_time', '>', $time)->count();
            if ($q_num >= 10) {
                self::$err_code = 400084;
                throw new \Exception('FAULT');
            }
            db('query_bank_log')->insert(['member_id' => $param['member_id'], 'add_time' => time()]);
            
            // 检查银行卡是否已经查询过了
            $bank_info = db('query_bank_info')->where('num', $param['num'])->find();
            if (!$bank_info) {
                // 调用第三方接口查询
                $query_url = "http://bankcardsilk.api.juhe.cn/bankcardsilk/query.php?num=" . $param['num'] . '&key=71dbd5da08f996f768197c846fee3935';
                $q_data = file_get_contents($query_url);
                $q_data = json_decode($q_data, true);
                if ($q_data['reason'] !== 'success') {
                    self::$err_code = 400085;
                    // 添加系统日志
                    $msg = '用户' . $param['member_id'] . '查询银行卡失败，失败原因' . $q_data['reason'];
                    add_system_log($msg);
                    throw new \Exception('FAULT');
                }

                // 将logo保存到本地
                //auto_save_image("http://images.juheapi.com/banklogo/" . $q_data['result']['logo'], '/' . $q_data['result']['tel']. '.jpg');
                getImage("http://images.juheapi.com/banklogo/" . $q_data['result']['logo'], $q_data['result']['tel']. '.jpg');
                $bank_info = [
                    'member_id' => $param['member_id'],
                    'num' => $param['num'],
                    'bank' => $q_data['result']['bank'],
                    'logo' => 'bank/logo/' . $q_data['result']['tel']. '.jpg',
                    'type' => $q_data['result']['type'],
                    'add_time' => time()
                ];
                db('query_bank_info')->insert($bank_info);  // 保存查询的信息
            }
            return ['code' => 200, 'data' => $bank_info, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 实名认证银行卡， 内部调用
    static public function certification_bank($param) {
        if(!isset($param['num']) || !isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $cache_name = 'certification_bank_'.$param['member_id'] . date('Ymd');
            $num = cache($cache_name) ? cache($cache_name) : 0;
            if ($num >= 10) {
                self::$err_code = 400087;
                throw new \Exception('FAULT');
            }
            $num++;
            cache($cache_name, $num);
            // 开始实名认证
            $host = "http://lundroid.market.alicloudapi.com";
            $path = "/lianzhuo/verifi";
            $method = "GET";
            $appcode = "23b6b7fe2b9840168b2ce4bfe06c2075";
            $headers = array();
            array_push($headers, "Authorization:APPCODE " . $appcode);
            $querys = 'acct_pan=' . $param['num'];
            if ($param['phone_num']) { $querys .= '&phone_num=' . $param['phone_num']; }
            if ($param['acct_name']) { $querys .= '&acct_name=' . $param['acct_name']; }
            if ($param['cert_id']) { $querys .= '&cert_id=' . $param['cert_id']; }
            $bodys = "";
            $url = $host . $path . "?" . $querys;

            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HEADER, true);
            if (1 == strpos("$".$host, "https://"))
            {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }
            $rs =  curl_exec($curl);
            $rs = substr($rs, strpos($rs, '{'));
            $rs = json_decode($rs, true);
            if ($rs['resp']["desc"] == 'OK' ) {
                return ['code' => 200, 'msg' => 'SUCCESS'];
            } else {
                self::$err_code = 400086;
                throw new \Exception('FAULT');
            }
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }
}
